package com.ybe.handler.http;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.ybe.exception.BadRequest;
import com.ybe.exception.Unauthorized;
import com.ybe.handler.exchange.HttpExchangeHandler;
import com.ybe.handler.exchange.HttpExchangeHandlerFactory;
import com.ybe.util.HttpExchangeUtil;

import java.io.IOException;

/**
 * RootPathRouterHandler
 */
public class RootPathRouterHandler implements HttpHandler {

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        try {
            HttpExchangeHandler matchHandler = HttpExchangeHandlerFactory.getMatchHandler(exchange);
            if(matchHandler != null){
                matchHandler.handler(exchange);
            }
            else {
                HttpExchangeUtil.sendText(exchange, 404, "Not Found URI");
            }
        } catch (BadRequest e) {
            System.out.println(e.getMessage());
            HttpExchangeUtil.sendText(exchange, 400, e.getMessage());
        } catch (Unauthorized e) {
            System.out.println(e.getMessage());
            HttpExchangeUtil.sendEmpty(exchange, 401);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            HttpExchangeUtil.sendText(exchange, 500, "Internal Server Error");
        } finally {
            exchange.close();
        }
    }
}
